package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import com.teach.javafxclient.util.HttpUtil;
import javafx.beans.value.ChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TabPane;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.scene.shape.Circle;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import kong.unirest.json.JSONArray;
import kong.unirest.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Liang Jianlin
 * @date 2024-03-30 14:28
 */
public class InnovationAndPracticeController {
    public Button contest;
    public Button volunteering;
    public Button innovation;
    public Button socialPractice;
    @FXML
    private HBox root;
    @FXML
    private VBox mainContent,publish;
    @FXML
    private VBox subContent;
    private Double pageHeight;
    private ChangeListener<Number> heightListener;
    private ChangeListener<Number> widthListener;
    private Double pageWidth;
    private TabPaneController tabC;
    private Map<String ,JSONArray> activityMap = new HashMap<>();
    private FXMLLoader tabLoader;
    private TabPane tabNode;
    @FXML
    public HBox finishedH;
    @FXML
    public HBox takingH;
    @FXML
    public HBox takingMoreH;
    @FXML
    public HBox finishedMoreH;
    @FXML
    private ScrollPane scrollF;
    @FXML
    private ScrollPane scrollT;
    @FXML
    private FlowPane takingItems;
    @FXML
    Button takingMore;
    @FXML
    Button finishedMore;
    @FXML
    private FlowPane finishedItems;
    @FXML
    public void initialize() throws IOException {
        root.heightProperty().addListener((observable, oldValue, newValue) -> {
            pageHeight = newValue.doubleValue();
            System.out.println(pageHeight+"hhh");
        });
        root.widthProperty().addListener((observable, oldValue, newValue) -> {
            pageWidth = newValue.doubleValue();
            System.out.println(pageWidth+"www");
        });

        contest.setOnAction(e-> {
            try {
                setActivityButton("contest");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        volunteering.setOnAction(e-> {
            try {
//                takingItems.getChildren().clear();
//                finishedItems.getChildren().clear();
                setActivityButton("volunteering");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        innovation.setOnAction(e-> {
            try {
                setProjectButton("innovation");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        socialPractice.setOnAction(e-> {
            try {
                setProjectButton("social-practice");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        //用来添加活动的语句，第一个是是名字，第二个是时间，第三个是图片路径，最后一个是所放的展示栏位置，takingItems就是进行中的活动，finishedItems就是已经结束的活动
        //TODO:添加活动卡片，测试用，等待删除修改

//        setIntroCard("第16届全国大学生数学竞赛","04-13","/com/teach/javafxclient/picture/屏幕截图 2024-03-30 232903.png",takingItems);
        takingMore.setOnAction(e -> {
            try {
                blankOpenOrClose((Button)e.getSource(),finishedMore,takingItems,finishedItems,finishedH,finishedMoreH,scrollT,scrollF);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        finishedMore.setOnAction(e -> {
            try {
                blankOpenOrClose((Button)e.getSource(),takingMore,finishedItems,takingItems,takingH,takingMoreH,scrollF,scrollT);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

//TODO:能用到
//        tabC.changeContentByScene(setActivityInfo("文艺活动","十佳歌手","05-26","6/26~当日","知新楼一楼","歌手比赛"),"singerCompetition","十佳歌手");

        //添加宽度监听器，在别的需要使用tabPane的页面里面也可以使用mainContent和subContent
        widthListener = (observable, oldValue, newValue) -> {
            pageWidth = newValue.doubleValue();
            System.out.println(pageWidth);
            mainContent.setPrefWidth(pageWidth*0.52);
            subContent.setPrefWidth(pageWidth*0.48);
        };
        root.widthProperty().addListener(widthListener);
    }
    //控制展示栏开关的方法
    //TODO:更改展示逻辑
    private void blankOpenOrClose(Button source, Button b2, FlowPane blank1, FlowPane blank2, HBox h, HBox h2, ScrollPane s, ScrollPane s2) throws IOException {
        if(source.getText().equals("查看更多....")){
            source.setText("收起");
            mainContent.setPrefHeight(pageHeight);
            subContent.setPrefHeight(pageHeight);
            blank1.setPrefHeight(pageHeight - 320);
            s.setPrefHeight(pageHeight - 325);
            heightListener = (observable, oldValue, newValue) -> {
                pageHeight = newValue.doubleValue();
                System.out.println(pageHeight);
                mainContent.setPrefHeight(pageHeight);
                subContent.setPrefHeight(pageHeight);
                blank1.setPrefHeight(pageHeight - 320);
                s.setPrefHeight(pageHeight - 325);
            };
            root.heightProperty().addListener(heightListener);
//            blank1.setPrefHeight(pageHeight - 400);
//            s.setPrefHeight(pageHeight - 405);
            b2.setVisible(false);
            b2.setManaged(false);
            blank2.setVisible(false);
            blank2.setManaged(false);
            h.setVisible(false);
            h.setManaged(false);
            h2.setVisible(false);
            h2.setManaged(false);
            s2.setVisible(false);
            s2.setManaged(false);
            //这里只是模拟
        }
        else if(source.getText().equals("收起")){
            root.heightProperty().removeListener(heightListener);
            source.setText("查看更多....");
            blank1.setPrefHeight(200);
            s.setPrefHeight(203);
            b2.setVisible(true);
            b2.setManaged(true);
            blank2.setVisible(true);
            blank2.setManaged(true);
            h.setVisible(true);
            h.setManaged(true);
            h2.setVisible(true);
            h2.setManaged(true);
            s2.setVisible(true);
            s2.setManaged(true);
        }
    }
    //用来添加活动简略信息展示卡片的方法，如果要修改可以去activity-intro.fxml和ActivityIntroController进行修改排版和添加修改属性
    public void setIntroCard(String name , String time, long id,FlowPane s) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/activity-intro.fxml"));
        Parent baseRoot = fxmlLoader.load();
        s.getChildren().add(baseRoot);
        ActivityIntroController c = fxmlLoader.getController();
        Image img;
        img = new Image(getClass().getResource("/com/teach/javafxclient/picture/用户-圆.png").toExternalForm());
        double wid = Math.min(img.getWidth() , img.getHeight());
        Rectangle2D viewport = new Rectangle2D(img.getWidth()/2 - wid/2, img.getHeight()/2 - wid/2, wid, wid);
        c.cover.setViewport(viewport);
        c.cover.setImage(img);
        c.nameLabel.setText(name);
        c.timeLabel.setText(time);
        baseRoot.setOnMouseClicked(e->{
            if (subContent.getChildren().isEmpty()) {
                tabLoader = new FXMLLoader(MainApplication.class.getResource("base/tab-pane.fxml"));
                try {
                    tabNode = tabLoader.load();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                ChangeListener<Number> widthListener;
                widthListener = (observable, oldValue, newValue) -> {
                    Double pageWidth = newValue.doubleValue();
                    System.out.println(pageWidth);
//                    mainContent.setPrefWidth(pageWidth*0.52);
                    subContent.setPrefWidth(pageWidth * 0.30);
                };
                root.widthProperty().addListener(widthListener);
                tabC = tabLoader.getController();
                subContent.getChildren().add(tabNode);

            }
            //FIXME:改
            try {
                tabC.changeContentByScene(setActivityInfo(id),name,name);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
    }
    //用来设置活动详情信息页面的方法，如果要修改可以去activity-info.fxml和ActivityInfoController进行修改排版和添加修改属性
    public Scene setActivityInfo(long id) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/activity-info.fxml"));
        Parent root = fxmlLoader.load();
        ActivityInfoController c = fxmlLoader.getController();
//        String id0= String.valueOf(id);
        HttpResponse<JsonNode> response = HttpUtil.get(Globalvar.baseUrl + "/api/activities/"+id)
                .header("Accept", "application/json")
                .asJson();
        JsonNode jsonResponse = response.getBody();
        System.out.println(jsonResponse.toString());
        JSONObject jsonObject = jsonResponse.getObject();
        System.out.println(jsonObject);
        String name0=jsonObject.getString("name");
        String type0=jsonObject.getString("type");
        String start0=jsonObject.getString("start");
        String end0=jsonObject.getString("end");
        String description0=jsonObject.getString("description");
        c.name.setText(name0);
        if (type0.equals("CONTEST")) {
            c.type.setText("活动类型：竞赛");
        } else {
            c.type.setText("活动类型：志愿活动");
        }
        c.description.setWrapText(true);
        c.description.setText("简介："+description0);


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        LocalDateTime startDateTime = LocalDateTime.parse(start0, formatter);
        LocalDateTime endDateTime = LocalDateTime.parse(end0, formatter);
        DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        c.start.setText("开始时间："+startDateTime.format(displayFormatter));
        c.end.setText("结束时间："+endDateTime.format(displayFormatter));
        Scene scene = new Scene(root);
        return scene;
    }
//    private void setActivityButton(String type) throws IOException {
//        JSONArray Arr = activityMap.get(type);
//        if(Arr==null) {
//            JSONArray res = HttpUtil.get(Globalvar.baseUrl + "/api/activities?type="+type)
//                    .header("Content-Type", "application/json")
//                    .asJson().getBody().getArray();
//            Arr = res;
//        }
//        for (int i = 0; i < Arr.length(); i++) {
////            if(!Arr.getJSONObject(i).getBoolean("completed")){
////                setIntroCard(Arr.getJSONObject(i).getString("name"),Arr.getJSONObject(i).getString("start"),Arr.getJSONObject(i).getString("poster"),(Long) Arr.getJSONObject(i).get("id"),takingItems);
////            }else {
////                setIntroCard(Arr.getJSONObject(i).getString("name"),Arr.getJSONObject(i).getString("start"),Arr.getJSONObject(i).getString("poster"),(Long) Arr.getJSONObject(i).get("id"),finishedItems);
////            }
//            if(!Arr.getJSONObject(i).getBoolean("completed")){
//                setIntroCard(Arr.getJSONObject(i).getString("name"),Arr.getJSONObject(i).getString("start"), Long.parseLong(Arr.getJSONObject(i).getString("id")),takingItems);
//            }else {
//                setIntroCard(Arr.getJSONObject(i).getString("name"),Arr.getJSONObject(i).getString("start"), Long.parseLong(Arr.getJSONObject(i).getString("id")),finishedItems);
//            }
//        }
//    }
private String selectedButtonType = ""; // Track the currently selected button type

//    public void setActivityButton(String type) throws IOException {
//        if (!selectedButtonType.isEmpty()) {
//            takingItems.getChildren().clear();
//            finishedItems.getChildren().clear();
//        }
//        selectedButtonType = type;
//
//        JSONArray Arr = activityMap.get(type);
//        if (Arr == null) {
//            JSONArray res = HttpUtil.get(Globalvar.baseUrl + "/api/activities?type=" + type)
//                    .header("Content-Type", "application/json")
//                    .asJson()
//                    .getBody()
//                    .getArray();
//            Arr = res;
//        }
//
//        for (int i = 0; i < Arr.length(); i++) {
//            if (!Arr.getJSONObject(i).getBoolean("completed")) {
//                setIntroCard(Arr.getJSONObject(i).getString("name"), Arr.getJSONObject(i).getString("start"),
//                        Long.parseLong(Arr.getJSONObject(i).getString("id")), takingItems);
//            } else {
//                setIntroCard(Arr.getJSONObject(i).getString("name"), Arr.getJSONObject(i).getString("start"),
//                        Long.parseLong(Arr.getJSONObject(i).getString("id")), finishedItems);
//            }
//        }
//    }
public void setActivityButton(String type) throws IOException {
    if (!selectedButtonType.isEmpty()) {
        takingItems.getChildren().clear();
        finishedItems.getChildren().clear();
        ObservableList<Node> children = takingItems.getChildren();

        for (Node child : children) {
            if (child instanceof VBox && child.getId() != null && child.getId().equals("publish")) {
                continue;
            }
            children.remove(child);
        }
    }
    selectedButtonType = type;
    JSONArray Arr = activityMap.get(type);
    if (Arr == null) {
        JSONArray res = HttpUtil.get(Globalvar.baseUrl + "/api/activities?type=" + type)
                .header("Content-Type", "application/json")
                .asJson()
                .getBody()
                .getArray();
        Arr = res;
    }

    for (int i = 0; i < Arr.length(); i++) {
        if (!Arr.getJSONObject(i).getBoolean("completed")) {
            setIntroCard(Arr.getJSONObject(i).getString("name"), Arr.getJSONObject(i).getString("start"),
                    Long.parseLong(Arr.getJSONObject(i).getString("id")), takingItems);
        } else {
            setIntroCard(Arr.getJSONObject(i).getString("name"), Arr.getJSONObject(i).getString("start"),
                    Long.parseLong(Arr.getJSONObject(i).getString("id")), finishedItems);
        }
    }
}
    private void setProjectButton(String type) throws IOException {
        JSONArray Arr = activityMap.get(type);
        if(Arr==null) {
            JSONArray res = HttpUtil.get(Globalvar.baseUrl + "/api/projects?type="+type)
                    .header("Content-Type", "application/json")
                    .asJson().getBody().getArray();
            Arr = res;
        }
        for (int i = 0; i < Arr.length(); i++) {
//            if(!Arr.getJSONObject(i).getBoolean("completed")){
//                setIntroCard(Arr.getJSONObject(i).getString("name"),Arr.getJSONObject(i).getString("start"),Arr.getJSONObject(i).getString("poster"), (Long) Arr.getJSONObject(i).get("id"),takingItems);
//            }else {
//                setIntroCard(Arr.getJSONObject(i).getString("name"),Arr.getJSONObject(i).getString("start"),Arr.getJSONObject(i).getString("poster"),(Long) Arr.getJSONObject(i).get("id"),finishedItems);
//            }
            if(!Arr.getJSONObject(i).getBoolean("completed")){
                setIntroCard(Arr.getJSONObject(i).getString("name"),Arr.getJSONObject(i).getString("start"), Long.parseLong(Arr.getJSONObject(i).getString("id")),takingItems);
            }else {
                setIntroCard(Arr.getJSONObject(i).getString("name"),Arr.getJSONObject(i).getString("start"), Long.parseLong(Arr.getJSONObject(i).getString("id")),finishedItems);
            }
        }
    }
};